<template>
  <div class="number-display">
    <span v-for="(digit, index) in formattedDigits" :key="index" class="digit-container">
      <transition name="digit-slide">
        <span :key="digit.current" class="digit">{{ digit.current }}</span>
      </transition>
    </span>
    <span class="decimal-point">.</span>
    <span v-for="(digit, index) in formattedDecimals" :key="'decimal-'+index" class="digit-container">
      <transition name="digit-slide">
        <span :key="digit.current" class="digit">{{ digit.current }}</span>
      </transition>
    </span>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  value: {
    type: Number,
    required: true
  },
  oldValue: {
    type: Number,
    required: true
  }
})

// 将数字拆分为整数部分和小数部分
const splitNumber = (num) => {
  const parts = num.toFixed(2).split('.')
  return {
    integer: parts[0].split('').map(Number),
    decimal: parts[1].split('').map(Number)
  }
}

// 格式化数字为可动画的数组
const formatDigits = (num, oldNum) => {
  const current = splitNumber(num)
  const old = splitNumber(oldNum)
  
  // 处理整数部分
  const integerDigits = current.integer.map((digit, i) => ({
    current: digit,
    old: old.integer[i] || 0,
    changed: digit !== (old.integer[i] || 0)
  }))
  
  // 处理小数部分
  const decimalDigits = current.decimal.map((digit, i) => ({
    current: digit,
    old: old.decimal[i] || 0,
    changed: digit !== (old.decimal[i] || 0)
  }))
  
  return { integerDigits, decimalDigits }
}

const formattedDigits = computed(() => formatDigits(props.value, props.oldValue).integerDigits)
const formattedDecimals = computed(() => formatDigits(props.value, props.oldValue).decimalDigits)
</script>

<style scoped>
.number-display {
  display: inline-flex;
  align-items: center;
  font-family: monospace;
  font-size: 24px;
  line-height: 1;
}

.digit-container {
  display: inline-block;
  position: relative;
  height: 1em;
  width: 0.6em;
  overflow: hidden;
  text-align: center;
}

.digit {
  display: block;
  position: absolute;
  width: 100%;
}

/* 向上滑出动画 */
.digit-slide-enter-active,
.digit-slide-leave-active {
  transition: all 0.4s ease;
}

.digit-slide-enter-from {
  transform: translateY(100%);
  opacity: 0;
}

.digit-slide-enter-to {
  transform: translateY(0);
  opacity: 1;
}

.digit-slide-leave-from {
  transform: translateY(0);
  opacity: 1;
}

.digit-slide-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}

.decimal-point {
  margin: 0 2px;
}
</style>